package cn.uway.netty.utils;

public class ByteUtils {

	 public static String byte2HexString(byte[] array){
	    	StringBuffer sb = new StringBuffer();
			for(int i=0;i<array.length;i++){
				String hex = Integer.toHexString(array[i] & 0xFF); 
			     if (hex.length() == 1) { 
			         hex = '0' + hex; 
			     }
			     sb.append(hex);
			}
			return sb.toString();
	    }
	    
	    public static byte[] hexStringToBytes(String hexString) {   
	        if (hexString == null || hexString.equals("")) {   
	            return null;   
	        }   
	        hexString = hexString.toUpperCase();   
	        int length = hexString.length() / 2;   
	        char[] hexChars = hexString.toCharArray();   
	        byte[] d = new byte[length];   
	        for (int i = 0; i < length; i++) {   
	            int pos = i * 2;   
	            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));   
	        }   
	        return d;   
	    } 
	    

	    public static byte charToByte(char c) {   
	        return (byte) "0123456789ABCDEF".indexOf(c);   
	    }  
	    
	    public static byte[] byteArraySub(byte[] array, int srcPos, int len){    	
	        byte[] newData = new byte[len];
	        if(len>array.length){
	        	len = array.length;
	        }
	        System.arraycopy(array, srcPos, newData, 0, len);  
	        return newData;
	    }   
	    
	    public static void main(String[] args) {
			byte[] a = {1,2,3,4,5,6,7};
			byte[] b = byteArraySub(a, 3, a.length-3);
			for(byte c : b){
				System.out.println(c);
			}
		}
}
